package com.roy.netty.sworddemo.server;

import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOption;
import io.netty.channel.SimpleChannelInboundHandler;

public class ByteArrayEngineHandler extends SimpleChannelInboundHandler<byte[]> {

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, byte[] data)
			throws Exception {
		String message  = new String(data);
		System.out.println("received message: "+ message);
		String responseMessage = "response message from server : "+message + " response";
		ChannelFuture writeFuture = ctx.writeAndFlush(responseMessage.getBytes());
		if (!isKeepAlive(ctx.channel())) {
            writeFuture.addListener((ChannelFutureListener) closeFuture -> {
                System.out.println("Closing not keepAlived connection "+closeFuture.channel());
                closeFuture.channel().close();
            });
        }
	}

	private boolean isKeepAlive(Channel channel) {
		 if (!channel.isOpen())
	            return false;
	        return channel.config().getOption(ChannelOption.SO_KEEPALIVE);
	}

}
